package cn.lblbc.numberguesser

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
    private var targetNumber: Int = 0
    private var attempts: Int = 0
    private lateinit var guessInput: EditText
    private lateinit var guessButton: Button
    private lateinit var resultText: TextView
    private lateinit var resetButton: Button
    private lateinit var attemptsText: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        initViews()
        startNewGame()
        setupListeners()
    }

    private fun initViews() {
        guessInput = findViewById(R.id.guessInput)
        guessButton = findViewById(R.id.guessButton)
        resultText = findViewById(R.id.resultText)
        resetButton = findViewById(R.id.resetButton)
        attemptsText = findViewById(R.id.attemptsText)
    }

    private fun startNewGame() {
        targetNumber = Random.nextInt(1, 101) // 生成1到100之间的随机数
        attempts = 0
        resultText.text = ""
        guessInput.text.clear()
        attemptsText.text = "已猜测次数: $attempts"
        guessInput.isEnabled = true
        guessButton.isEnabled = true
    }

    private fun setupListeners() {
        guessButton.setOnClickListener {
            makeGuess()
        }

        resetButton.setOnClickListener {
            startNewGame()
        }
    }

    private fun makeGuess() {
        val input = guessInput.text.toString()
        if (input.isEmpty()) {
            Toast.makeText(this, "请输入一个数字", Toast.LENGTH_SHORT).show()
            return
        }

        val guess = input.toIntOrNull()
        if (guess == null || guess < 1 || guess > 100) {
            Toast.makeText(this, "请输入1到100之间的数字", Toast.LENGTH_SHORT).show()
            return
        }

        attempts++
        attemptsText.text = "已猜测次数: $attempts"

        when {
            guess < targetNumber -> {
                resultText.text = "太小了！再试一次"
            }
            guess > targetNumber -> {
                resultText.text = "太大了！再试一次"
            }
            else -> {
                resultText.text = "恭喜你！猜对了！\n答案是 $targetNumber"
                guessInput.isEnabled = false
                guessButton.isEnabled = false
                Toast.makeText(this, "你用了 $attempts 次猜中了数字", Toast.LENGTH_LONG).show()
            }
        }
    }
}